<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="userQuery.userEntity.username" placeholder="用户名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="userQuery.userEntity.userId" placeholder="工号" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="userQuery.userEntity.telephone" placeholder="电话" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="userQuery.userEntity.userCharacter" placeholder="角色" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <br>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" size="medium" @click="handleCreate">
        增加
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-copy" size="medium" @click="handleCopyUsers">
        复制
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-delete" size="medium" @click="deleteUser">
        删除
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-add" size="medium" @click="allocateCharacter">
        分配角色
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="text">
        <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
          <el-submenu index="2">
            <template slot="title">启停控制</template>
            <el-menu-item index="published">启用</el-menu-item>
            <el-menu-item index="draft">停用</el-menu-item>
          </el-submenu>
        </el-menu>
      </el-button>
    </div>
    <el-container>
      <el-aside width="200px" class="left-aside" style="background-color: rgb(238, 241, 246);">
        <meau @nodeClicked="handleNodeClicked" @nodeNameClicked="handleNodeNames" />
      </el-aside>
      <!-- 数据表格组件，用于展示用户信息 -->
      <el-main>
        <el-table
          :key="tableKey"
          v-loading="listLoading"
          :data="list"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          :selectable="true"
          :default-sort="{prop: '工号', order: 'descending'}"
          @sort-change="sortChange"
          @select="handleSelectionChange"
          @select-all="handleSelectAll"
        >
          <!-- 选择列 -->
          <el-table-column
            type="selection"
            width="50"
          />
          <!-- 工号列 -->
          <el-table-column label="序号" align="center" width="60">
            <template slot-scope="{row, $index}">
              <span>{{ getRowIndex($index) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="工号" min-width="100px" align="center" sortable>
            <template slot-scope="{row}">
              <span>{{ row.userId }}</span>
            </template>
          </el-table-column>
          <!-- 用户名列 -->
          <el-table-column label="用户名" width="90px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.username }}</span>
            </template>
          </el-table-column>
          <!-- 所属公司列-->
          <el-table-column label="所属公司" min-width="110px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.company }}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属部门" width="100px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.department }}</span>
            </template>
          </el-table-column>
          <!-- 所属角色列 -->
          <el-table-column label="所属角色" min-width="100px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.roleList }}</span>
            </template>
          </el-table-column>
          <!-- 职位列 -->
          <el-table-column label="职位" width="70px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.position }}</span>
            </template>
          </el-table-column>
          <!-- 性别列 -->
          <el-table-column label="性别" width="60px" align="center">
            <template slot-scope="{row}">
              <span>{{ row.gender }}</span>
            </template>
          </el-table-column>
          <!-- 生日列，使用管道符进行日期格式化 -->
          <el-table-column label="生日" prop="生日" width="140px" align="center" sortable>
            <template slot-scope="{row}">
              <span>{{ row.birthday | parseTime2('{y}-{m}-{d} {h}:{i}') }}</span>
            </template>
          </el-table-column>
          <!-- 电话列 -->
          <el-table-column label="电话" align="center" width="95">
            <template slot-scope="{row}">
              <span>{{ row.telephone }}</span>
            </template>
          </el-table-column>
          <!-- 状态列，使用不同的标签显示不同状态 -->
          <el-table-column label="状态" class-name="status-col" width="90">
            <template slot-scope="{row}">
              <el-tag v-if="row.userStatus!='draft'" :type="row.userStatus | statusFilter">
                启用
              </el-tag>
              <el-tag v-if="row.userStatus=='draft'" :type="row.userStatus | statusFilter">
                停用
              </el-tag>
            </template>
          </el-table-column>
          <!-- 操作列，包括编辑、启用、停用和删除按钮 -->
          <el-table-column label="操作" align="center" width="290" class-name="small-padding fixed-width">
            <template slot-scope="{row,$index}">
              <el-button type="primary" size="mini" @click="handleCopy(row)">
                复制
              </el-button>
              <el-button type="primary" size="mini" @click="handleModify(row)">
                编辑
              </el-button>
              <el-button v-if="row.userStatus=='draft'" size="mini" type="success" @click="handleModifyStatus(row,'published')">
                启用
              </el-button>
              <el-button v-if="row.userStatus!='draft'" size="mini" @click="handleModifyStatus(row,'draft')">
                停用
              </el-button>
              <el-button v-if="row.userStatus!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="userQuery.pageIndex" :limit.sync="userQuery.pageSize" @pagination="getList" />
      </el-main>
      <!-- 新增、修改用户窗口 -->
      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
          <el-form-item label="工号" prop="userId">
            <el-input v-model="temp.userId" />
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="temp.username" />
          </el-form-item>
          <el-form-item v-if="showPassword" label="密码" prop="password">
            <el-input v-model="temp.password" />
          </el-form-item>
          <el-form-item label="性别">
            <el-select v-model="temp.gender" class="filter-item" placeholder="Please select">
              <el-option v-for="item in genderOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="电话" prop="telephone">
            <el-input v-model="temp.telephone" />
          </el-form-item>
          <el-form-item label="出生日期" prop="birthday">
            <el-date-picker v-model="temp.birthday" type="datetime" placeholder="Please pick a date" />
          </el-form-item>
          <el-form-item label="所属公司" prop="company">
            <el-input v-model="temp.company" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="temp.userStatus" class="filter-item" placeholder="Please select">
              <el-option v-for="item in statusOptions" :key="item" :label="statusCNMap[item]" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="职位">
            <el-select v-model="temp.position" class="filter-item" placeholder="Please select">
              <el-option v-for="item in positionOptions" :key="item.id" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属部门">
            <el-select v-model="temp.department" class="filter-item" placeholder="Please select">
              <el-option v-for="item in departmentOptions" :key="item.id" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
        <!-- <el-form-item label="备注">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="Please input" />
        </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            确定
          </el-button>
        </div>
      </el-dialog>
      <AllocationDialog ref="allocationDialog" @edit="updateCharacter" />
      <UserUpdateDialog ref="userUpdateDialog" @add="createData" />
      <UserAddDialog ref="userAddDialog" @edit="updateData" />
    </el-container>
  </div>
</template>

<script>
import { userUpdateArticle, userUpdateStatus, userAllocateCharacter, startUsersInfo, shutUsersInfo } from '@/action/userManagement/userUpdateAction.js'
import { getUserList, userSelectRoleList } from '@/action/userManagement/userGetAction.js'
import { userCreateArticle } from '@/action/userManagement/userAddAction.js'
import { deleteUserInfo, deleteUsersInfo } from '@/action/userManagement/userDeleteAction.js'
import waves from '@/directive/waves' // waves directive
import { parseTime, parseTime2 } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import AllocationDialog from './components/AllocationDialog.vue'
import UserUpdateDialog from './components/UserUpdateDialog.vue'
import UserAddDialog from './components/UserAddDialog.vue'
import Meau from '@/views/userManagement/components/Meau.vue'

export default {
  name: 'ComplexTable',
  components: { Pagination, AllocationDialog, UserUpdateDialog, UserAddDialog, Meau },
  directives: { waves },
  filters: {
    statusFilter(userStatus) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[userStatus]
    }
  },
  data() {
    return {
      copy: false,
      newCharacter: null,
      tableKey: 0,
      currentSelectedIndex: null,
      list: null,
      total: 0,
      listLoading: true,
      userQuery: {
        userEntity: {
          id: '',
          userId: '',
          username: '',
          password: '',
          birthday: '',
          userStatus: '',
          userCharacter: '',
          company: '',
          position: '',
          department: '',
          tenantId: '',
          companyId: '',
          gender: '',
          telephone: '',
          createdBy: '',
          createdTime: '',
          updatedBy: '',
          updatedTime: '',
          status: '',
          version: '',
          creator: '',
          modifier: ''
        },
        pageIndex: 1,
        pageSize: 20,
        userIdsList: [],
        idsList: [],
        roleIdsList: []
      },
      statusOptions: ['published', 'draft', 'deleted'],
      genderOptions: ['男', '女'],
      positionOptions: [],
      departmentOptions: [],
      statusCNMap: {
        'published': '启用',
        'draft': '停用',
        'deleted': '删除'
      },
      showPassword: true,
      allocationTable: null,
      // allocationTable: [
      //   { name: 'character1', id: '001', code: 'code1' },
      //   { name: 'character2', id: '002', code: 'code2' },
      //   { name: 'character3', id: '003', code: 'code3' }
      // ],
      temp: {
        id: undefined,
        userId: undefined,
        username: '',
        password: '',
        birthday: '',
        userStatus: 'published',
        userCharacter: '',
        company: '',
        position: '',
        department: '',
        tenantId: '',
        companyId: '',
        gender: '',
        telephone: '',
        createdBy: '',
        createdTime: new Date(),
        updatedBy: '',
        updatedTime: new Date(),
        status: '',
        version: '',
        creator: '',
        modifier: ''
      },
      dialogFormVisible: false,
      allocationVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      // 输入框输入限制条件
      rules: {
        userCharacter: [{ required: true, message: '所属角色是必填项', trigger: 'change' }],
        username: [{ required: true, message: '用户名是必填项', trigger: 'change' }],
        position: [{ required: true, message: '职位是必填项', trigger: 'change' }],
        userId: [{ required: true, message: '工号是必填项', trigger: 'change' }],
        department: [{ required: true, message: '所属部门是必填项', trigger: 'change' }],
        password: [{ required: true, message: '密码是必填项', trigger: 'change' }],
        telephone: [{ required: true, message: '电话是必填项', trigger: 'change' }],
        birthday: [{ type: 'date', required: true, message: '出生日期是必填项', trigger: 'change' }],
        company: [{ required: true, message: '所属公司是必填项', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /**
     * 获取用户列表。
     * 此函数没有参数。
     * 没有返回值，但会更新组件内的列表状态。
     */
    getList() {
      this.listLoading = true
      console.log(this.userQuery)
      getUserList(this.userQuery).then(response => {
        this.list = response.data
        const templist1 = response.data.slice((this.userQuery.pageIndex - 1) * this.userQuery.pageSize, this.userQuery.pageIndex * this.userQuery.pageSize)
        this.list = templist1
        this.total = response.total
        this.positionOptions = response.data[0].positionList
        this.departmentOptions = response.data[0].departmentList
        this.listLoading = false
      })
      console.log(this.list)
      console.log(this.total)
    },
    handleFilter() {
      this.userQuery.pageIndex = 1
      this.getList()
    },
    handleNodeClicked(id) {
      // const filteredNames = [id]
      // this.fiterList = this.list.filter(item => filteredNames.includes(item.parentNode))
    },
    handleNodeNames(names) {
      // console.log(names)
      // this.fiterList = this.list.filter(item => {
      //   const isIncluded = names.includes(item.parentNode)
      //   console.log(item.parentNode)
      //   console.log(`Item ${item.id} is included: ${isIncluded}`)
      //   return isIncluded
      // })
      // console.log(this.list)
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return parseTime2(v[j])
        }
      }))
    },
    /**
     * 更改用户状态
     */
    handleModifyStatus(row, userStatus) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.userStatus = userStatus
      this.resetTemp()
      this.temp.userId = row.userId
      this.temp.id = row.id
      this.temp.userStatus = userStatus
      userUpdateStatus(this.temp).then(() => {
        this.$notify({
          title: 'Success',
          message: 'Update Successfully',
          type: 'success',
          duration: 2000
        })
      })
      this.resetTemp()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    /**
     * 根据排序规则获取用户列表id排序
     */
    sortByID(order) {
      this.handleFilter()
    },
    /**
     * 更新选中的行
     */
    handleSelectionChange(selection, row) {
      // 更新选中的行
      this.selectedRows = selection
      console.log('当前选择的行:', this.selectedRows)
    },
    /**
     * 更新全选的行
     */
    handleSelectAll(selection) {
      // 更新全选的行
      this.selectedRows = selection
      console.log('全选:', this.selectedRows)
    },
    handleSelect(key, keyPath) {
      // 这里写删除请求
      const ids = this.selectedRows.map(row => row.id)
      this.selectedRows = []
      if (key === 'published') {
      // daixiugai
        startUsersInfo(ids).then(res => {
          this.$notify({
            title: 'Success',
            message: '修改成功！',
            type: 'success',
            duration: 2000
          })
          location.reload()
        })
      } else {
      // daixiugai
        shutUsersInfo(ids).then(res => {
          this.$notify({
            title: 'Success',
            message: '修改成功！',
            type: 'success',
            duration: 2000
          })
          location.reload()
        })
      }
    },
    /**
     * 批量删除用户
     */
    deleteUser() {
      this.$confirm('此操作将永久删除这些用户, 是否继续?', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        // 这里写删除请求
        const ids = this.selectedRows.map(row => row.id)
        this.list = this.list.filter(row => !ids.includes(row.id))
        this.selectedRows = []
        // daixiugai
        deleteUsersInfo(ids).then(res => {
          this.$notify({
            title: 'Success',
            message: '删除成功！',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        // 点击取消:不删除了
        this.$notify({
          title: 'Cancel',
          message: '已取消删除',
          type: 'info',
          duration: 2000
        })
      })
    },
    /**
     * 用户分配角色窗口开启
     */
    allocateCharacter() {
      userSelectRoleList().then(res => {
        this.$refs.allocationDialog.total = res.total
        this.$refs.allocationDialog.tableData = res.data
      })
      // this.$refs.allocationDialog.tableData = this.allocationTable
      this.$refs.allocationDialog.allocationVisible = true
    },
    /**
     * 更新用户分配角色
     */
    updateCharacter(character, allocateList) {
      this.newCharacter = character.name
      this.$refs.allocationDialog.allocationVisible = false
      this.userQuery.roleIdsList = allocateList
      console.log(allocateList)
      console.log(this.userQuery.roleIdsList)
      // 遍历 selectedRows 数组
      this.selectedRows.forEach(selectedRow => {
        // 使用 findIndex 查找 selectedRow 在 list 中的索引
        const index = this.list.findIndex(row => row.id === selectedRow.id)
        // 如果找到了索引（即 selectedRow 在 list 中存在）
        if (index !== -1) {
          // 更新 list 数组中对应行的 character 值
          this.list[index].userCharacter = this.newCharacter
        }
      })
      this.userQuery.userIdsList = this.selectedRows.map(row => row.userId)
      this.userQuery.idsList = this.selectedRows.map(row => row.id)
      this.userQuery.userEntity.userCharacter = this.newCharacter

      userAllocateCharacter(this.userQuery).then(() => {
        this.$notify({
          title: 'Success',
          message: '修改成功',
          type: 'success',
          duration: 2000
        })
        this.userQuery.userEntity.userCharacter = ''
      })
      // 如果你只是想清空 selectedRows 数组，而不实际删除 list 中的行
      this.selectedRows = []
      location.reload()
    },
    /**
     * 重置用户信息输入框
     */
    resetTemp() {
      this.temp = {
        id: undefined,
        userId: undefined,
        username: '',
        password: '',
        birthday: '',
        userStatus: 'published',
        userCharacter: '',
        company: '',
        position: '',
        department: '',
        tenantId: '',
        companyId: '',
        gender: '',
        telephone: '',
        createdBy: '',
        createdTime: new Date(),
        updatedBy: '',
        updatedTime: new Date(),
        status: '',
        version: '',
        creator: '',
        modifier: ''
      }
    },
    /**
     * 新建用户信息前置操作
     */
    handleCreate() {
      this.showPassword = true
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /**
     * 新建用户信息
     */
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.userCharacter = '戴圣燃'
          this.temp.gender = '男'
          this.temp.companyId = this.list[0].companyId
          this.temp.tenantId = this.list[0].tenantId
          userCreateArticle(this.temp).then(res => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
      this.created()
      location.reload()
    },
    handleCopy(row) {
      this.copy = true
      this.handleUpdate(row)
    },
    handleCopyUsers() {
      if (this.selectedRows.length > 0) {
        this.handleCopy(this.selectedRows[0])
      }
    },
    handleModify(row) {
      this.copy = false
      this.handleUpdate(row)
    },
    /**
     * 修改用户信息前置操作
     */
    handleUpdate(row) {
      this.showPassword = false
      if (this.copy) {
        this.showPassword = true
      }
      this.temp = Object.assign({}, row)
      this.temp.birthday = new Date(this.temp.birthday)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /**
     * 修改用户信息
     */
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (!this.copy) {
            const tempData = Object.assign({}, this.temp)
            console.log(tempData)
            tempData.birthday = +new Date(tempData.birthday) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            userUpdateArticle(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Update Successfully',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            // this.temp.userCharacter = '戴圣燃'
            // this.temp.gender = '男'
            this.temp.companyId = this.list[0].companyId
            this.temp.tenantId = this.list[0].tenantId
            this.copy = false
            userCreateArticle(this.temp).then(res => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
            })
          }
        }
      })
      this.created
      this.selectedRows = []
      location.reload()
    },
    /**
     * 删除单个用户信息
     */
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        // 这里写删除请求
        this.list.splice(index, 1)
        this.temp.userId = row.userId
        this.temp.id = row.id
        deleteUserInfo(this.temp).then(res => {
          this.$notify({
            title: 'Success',
            message: '删除成功！',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
        // 点击取消:不删除了
        this.$notify({
          title: 'Cancel',
          message: '已取消删除',
          type: 'info',
          duration: 2000
        })
      })
    },
    getRowIndex(index) {
      return (this.userQuery.pageIndex - 1) * this.userQuery.pageSize + index + 1
    }
  }
}
</script>
